(function ($) { 
jQuery.fn.extend({
import_data: function(options, _callback){
	var defaults = {
			  type			: null
			, ajax_url		: null
			, title			: null
			, sample_url	: null
			, callback		: null
			, event_name	: "click"
			, upload_url	: "./fileupload.php"
			, data			: {}
			, fields		: [] //CONTAINS OBJECTS {name:field-name, title:field-title, show_on_import:true/false, data:[{id: , name:}]}
		};
		
	options					= $.extend(true, {}, defaults, options);
	if (typeof _callback !== "undefined" && _callback != null)
		options.callback = _callback;
		
	var import_data			= [];
	var import_columns		= [];//CONTAINS OBJECTS {id:column-number, name: field-name}
	var row_count			= 0;
	var current_row			= 0;
	var start_row			= "";
	var processed_data		= [];
	var ignore_duplicates	= true;
	
	var _dlg = $('\
		<div title="Import">\
			<div class="ui-state-highlight screen-message">&nbsp;</div>\
			<ul>\
				<li><a href="#import_select_file">Select File</a></li>\
				<li><a href="#import_prepare_file">Prepare File</a></li>\
				<li><a href="#import_errors">Import Errors</a></li>\
			</ul>\
			<div id="import_select_file">\
				<div id="import_data_form">\
					<form action="./fileupload.php" method="post" enctype="multipart/form-data">\
						<input type="file" size=100 name="myfile"><br>\
						<input type="submit" id="import_load_file" style="width:200px;height:40px;" value="Load File">\
					</form>\
				</div>\
				<br/>\
				<br />\
				<p style="font-size:14px;font-weight:bold;">\
				<a id="import_sample_url" href="samples/members.csv">Click here to download a sample file</a>\
				</p>\
			</div>\
			<div id="import_prepare_file" style="border-bottom: 3px solid grey">\
				<fieldset>\
					<p>\
					<label for="import_has_header">First row is header</label>\
					<input id="import_has_header" type="checkbox" checked/>\
					</p>\
					<p>\
					<label for="ignore_duplicates">Ignore duplicates (in file)</label>\
					<input id="ignore_duplicates" type="checkbox" checked/>\
					</p>\
				</fieldset>\
				<p>\
					<button id="import_data_file" >Import File</button>\
				</p>\
				<div id="import_progress_label"></div>\
				<div id="import_progress_bar"></div>\
				<div id="import_result_table" style="width:100%;height:100%;display:inline-block;overflow:auto;"></div>\
			</div>\
			<div id="import_errors" ></div>\
		</div>');

	_dlg.dialog({
		autoOpen: false,
		height: 640,
		width: 850,
		modal: true
		, open:function(event, ui){
			__init_dialog();
		}
		, close: function() {}
	});
	
	if (options.upload_url){
		_dlg.find("#import_data_form form").attr("action", options.upload_url);
		
	}
	//SET EVENT HANDLER
	if (options.event_name){
		$(this)
			.unbind(options.event_name)
			.bind(options.event_name, function(){
				$(".left_panel_more").hide();
				show();
			});
	} else {
		show();
	}
	
	var _set_title = function(msg){
		var m = _dlg.find(".screen-message");
		m.show();
		m.html("<h3>"+msg+"</h3>");
	}
	
	function show(){
		if (options.sample_url == null || $.trim(options.sample_url) == "")
			_dlg.find("#import_sample_url").hide();
		else
			_dlg.find("#import_sample_url").show();
			
		_dlg.find("#import_sample_url").attr("href", options.sample_url);
		_dlg.dialog("option", "title", "Import "+options.title);
		_dlg.dialog("open");
		
	}
	
	function __init_dialog(){
		_dlg.tabs();
		_dlg.find("#import_data_file").button().unbind("click").click(function(){validate_data()});
		_dlg.find("#import_load_file").button();
		_dlg.find("#import_data_form").hide();
		_dlg.tabs({active:0});
		
		if (cache.default_client <= 0) return;
		
		_dlg.find("#import_data_form").show();
		_dlg.find("#import_result_table").children().remove();
		options.fields.sort(function(a, b){
			if (a.title < b.title)
				return -1;
			if (a.title > b.title)
				return 1;
			return 0;
		});
		
		//I DON'T LIKE THIS, BUT CURRENTLY DON'T KNOW HOW ELSE TO DO THIS :-(
		_dlg.find('form').ajaxForm({
			complete: function(xhr) {
				data = $.parseJSON(xhr.responseText);
				buildImportTable(data);
				import_data = data;
			}
		}); 
	}

	function generate_import_header_column(){
		select = $("<select></select>");
		select.append("<option value=''></option>");
		$(options.fields).each(function(){
			if (typeof this.show_on_import === "undefined" || this.show_on_import === false) return;
			
			var opt = $("<option value='"+this.name+"'>"+this.title+"</option>");
			opt.prop("field", this);
			select.append(opt);
			
		});
		
		return select;
	}

	function validate_data(){
		_dlg.find("#import_progress_bar").progressbar({value:0});
		var table = _dlg.find("#import_result_table").find("table");
		var thead = table.find("thead");
		var tr = table.find("tr").eq(0);
		var err_tbl = $("<table></table>");
		
		_dlg.find("#import_errors").children().remove();
		_dlg.find("#import_errors").append(err_tbl);
		err_tbl.append("<thead><tr><th>Row#</th><th>Field</th><th>Errors</th></tr></thead>");
		var err_body = $("<tbody></tbody>");
		err_tbl.append(err_body);
		_set_title("Validating data to be imported...");
		console.log("dump of cache");
		console.log(cache);
		tr.find("th").each(function(){
			select = $(this).find("select");
			col_type = select.find("option:selected").text();
			if (this.cellIndex > 0 && select.val() != ""){ //COLUMN ZERO IS THE ROW NUMBER
				import_columns.push(
					{id:this.cellIndex, name: select.val()}
					);
				var errors = [];
				var field_name = select.val();
				var field = select.find("option:selected").prop("field");
				
				//IF THERE IS A FOREIGN KEY, THEN GO AND CHECK
				//THE CACHE TO DO CLIENT-SIDE VALIDATIONS
				if (field.foreign_key){
					if (field.foreign_key.sql_table in cache){
						console.log(field.foreign_key.sql_table+" does exist");
						console.log(field);
						field.data = cache[field.foreign_key.sql_table];
					}
				}
				if (typeof field.data !== "undefined" && field.data != null){
					errors = validate_column_type(this.cellIndex, err_body, col_type, field_name, field.data, field.foreign_key.value);
					import_columns[import_columns.length-1].data = field.data;
				}
			}
		});
		hide_title();
		update_table_format(err_tbl);
		if (err_body.find("tr").length != 0)
			_dlg.tabs({active:2});//.height($(document).height()*0.5);
		else{
			//DO THE ACTUAL IMPORT
			var ignore_duplicates	= _dlg.find("#ignore_duplicates").is(":checked");
			var tbl					= _dlg.find("#import_result_table").find("tbody");
			start_row				= _dlg.find("#import_has_header").is(":checked") ? ":gt(0)" : "";
			
			current_row = 0;
			if (start_row != "") current_row++;
			row_count = tbl.find("tr"+start_row).length;
			
			_dlg.find("#import_progress_label").children().remove();
			_dlg.find("#import_progress_label").append("<h1>Importing data</h1>");
			_dlg.find("#import_progress_bar").progressbar({value:0});

			ignore_duplicates = _dlg.find("#ignore_duplicates").is(":checked");
			processed_data = [];
			import_data_send_to_server();

		}
	}

	function in_array(obj, arr_list){
		//console.log("trying to find: "+JSON.stringify(obj));
		//DOES NOT DEAL WITH NESTED ARRAYS.....NOT OF INTEREST IN MY PROJECT.
		for(var index = 0; index < arr_list.length; index++){
			var item = arr_list[index];
			//console.log("\t\t"+JSON.stringify(item));
			if (typeof(obj) === typeof(item)){
				var same = true;	//ASSUME IT IS THE SAME
				
				for(key in obj){
					if (typeof(item[key]) === "undefined") {
						same = false;
					} else if (typeof(item[key]) !== typeof(obj[key])) {
						same = false;
					} else if (item[key] !== obj[key]) {
						same = false;
					}
				}
				
				if (same == true) return true;
			}
		}
		
		return false;
	}
	
	function import_data_send_to_server(){
		var row_index				= 0;
		var tbl						= _dlg.find("#import_result_table").find("tbody");
		var request = {
				  ajax_url			: options.ajax_url
				, server_call		: options.server_call
				, ignore_duplicates : _dlg.find("#ignore_duplicates").is(":checked")
				, data				: options.data
			};
		
		request.data = {};
		$(options.fields).each(function(){
			request.data[this.name] = null;
		});
		
		var row = tbl.find("tr").eq(current_row);
		var empty_row = true;
		
		$(import_columns).each(function(){
			value = null;
			col = $(row).find("td").eq(this.id);
			value = $.trim(col.html());
			if (typeof value != "undefined" && value != "") empty_row = false;
			
			if (this.data != null){
				request.data[this.name] = import_get_key_from_name(value, this.data);
			}
			else
				request.data[this.name] = value;
		});
		
		$(row).addClass("ui-state-highlight");
		
		_dlg.find("#import_progress_bar").progressbar({value:(current_row/row_count)*100});
		
		var post_import = function(data){
				if (current_row <= row_count){
					current_row++;
					if (typeof options.callback == "function" && !empty_row){
						options.callback(data);
					}
					import_data_send_to_server();
				} else {
					_set_title("Import Complete");
				}
				
				//hide_title();
			};

		if (!empty_row){
			if (true == ignore_duplicates){
				//console.log("checking for duplicates");
				if (true == in_array(request.data, processed_data)){
					post_import(request.data);
					return; //JUMP OUT
				}
			}
			
			processed_data.push(request.data);
			_set_title("Importing row "+current_row);
			if (request.ajax_url != null && request.ajax_url != ""){
				get_server_data(request, function(data){
					post_import(data);
				});
			} else {
				//console.log("calling post_import");
				post_import(request.data);
			}
		}
		else {
			console.log("*****ROW IS EMPTY*********");
			post_import(request.data);
			//hide_title();
		}
	}

	function import_get_key_from_name(name, data_set){
		result = null;
		$(data_set).each(function(){
			if (unescape(this.name).toLowerCase() == value.toLowerCase()){
				result = this.id;
			}
		});
		
		if (null == result){
			console.log("Could not find: "+name);
		}
		
		return result;
	}

	function validate_column_type(col_index, err_body, col_type, field_name, data_set, search_field){
		var row_index = 1;
		var tbl = _dlg.find("#import_result_table tbody");
		var start_row = _dlg.find("#import_has_header").is(":checked") ? ":gt(0)" : "";
		_dlg.find("#import_progress_label").children().remove();
		_dlg.find("#import_progress_label").append("<h1>Validating "+ col_type+"</h1>");
		_dlg.find("#import_progress_bar").progressbar({value:0});
		row_cnt = tbl.find("tr:gt(0)").length;
		if (start_row != "") row_index++;
		if (typeof search_field === "undefined") search_field = "name";

		console.log(field_name+" ==> "+search_field);
		//if (data_set) console.log(data_set);
		
		tbl.find("tr"+start_row).each(function(){
			value = null;
			col = $(this).find("td").eq(col_index);
			value = col.text();
			if (typeof value == "undefined") return;
			if ($.trim(value) == "") return;
			
			_dlg.find("#import_progress_bar").progressbar({value:(row_index/row_cnt)*100});
			var found_it = false;
			//console.log(field_name+" ==> "+search_field+" == VALUE ["+value+"]");
			$(data_set).each(function(){
				console.log("\t\t"+this[search_field]+" == "+value);
				if ($.trim((this[search_field]).toLowerCase()) == $.trim((value).toLowerCase())){
					found_it = true;
				}
			});
			
			if (field_name.toLowerCase() == "name"){
				if (value.length > 150){
					err_body.append("<tr><td>"+row_index+"</td><td>"+col_type+"</td><td>Text must be less than 50 characters: "+value+"</td></tr>");
				}
			}
			else{
				if (false == found_it){
					err_body.append("<tr><td>"+row_index+"</td><td>"+col_type+"</td><td>Item not found: "+value+"</td></tr>");
				}
			}
			row_index++;
		});
	}

	function buildImportTable(data){
		var tbl = $("<table style='height:300px;overflow:auto;display:inline-block;'>");
		var thead = $("<thead>");
		var tbody = $("<tbody>");
		var tr = $("<tr>");
		thead.append(tr);
		
		tbl.append(thead);
		tbl.append(tbody);
		tr.append("<th>#</th>");
		$(data[0]).each(function(){
			var td = $("<th>").append(generate_import_header_column());
			
			tr.append(td);
		});
		row_cnt = 1;
		$(data).each(function(){
			var tr = $("<tr>");
			tbody.append(tr);
			tr.append("<td>"+row_cnt+"</td>");
			$(this).each(function(){
				tr.append("<td>"+this+"</td>");
			});
			row_cnt++;
		});
		update_table_format(tbl);
		_dlg.find("#import_result_table").children().remove();
		_dlg.find("#import_result_table").append(tbl);
		_dlg.tabs({active:1});//.height($(document).height());

		//ONLY LOAD OTHER DATA BASED ON GROUP SELECTED
		//MAKE SURE THE TABLE IS FITTED INTO THE DIALOG

		//tbl.css({overflow: "auto", display:"block", height: (_dlg.dialog("option", "height")*0.5 ), width: _dlg.dialog("option", "width") - 50});
		//tbl.resizable();
		//_dlg.find("#import_result_table").resizable();
	}
}
});
})(jQuery);
